<template>
  <n-modal
    v-model:show="getProps.modalData.show"
    class="custom-card"
    preset="card"
    :style="{ width: '800px' }"
    :title="title"
    :bordered="false"
    :segmented="{
      content: true,
      footer: true
    }"
  >
    <n-form ref="formRef" :model="form" label-placement="left" :label-width="160" :rules="rules">
      <n-form-item label="营业执照上传" path="licenseUrl">
        <x-upload
          v-model:value="form.licenseUrl"
          action="/api/file/upload"
          :limit="1"
          :validate="{
            fileSize: 2 * 1024
          }"
          accept=".jpg,.jpeg,.png"
          restriction-text="最多上传1张图片支持jpg、jpeg、png，图片大小不超2M"
        >
        </x-upload>
      </n-form-item>
      <n-form-item label="公司名称" path="companyName">
        <n-input v-model:value="form.companyName" placeholder="请输入公司营业执照上的名称" type="text" clearable />
      </n-form-item>
      <n-form-item label="联系人" path="accountName">
        <n-input v-model:value="form.accountName" placeholder="请输入联系人" type="text" clearable />
      </n-form-item>
      <n-form-item label="联系电话" path="accountMobile">
        <n-input v-model:value="form.accountMobile" type="text" clearable />
      </n-form-item>
      <n-form-item label="登录邮箱" path="accountMailbox">
        <n-input v-model:value="form.accountMailbox" type="text" clearable />
      </n-form-item>
      <n-form-item label="登录密码" path="accountPassword">
        <n-space align="center">
          <n-input-group>
            <n-input v-model:value="form.accountPassword" type="text" clearable />
            <x-button ghost @click="setPwd">自动生成</x-button>
          </n-input-group>
          <n-text>未填写新密码，则保存原来的密码</n-text>
        </n-space>
      </n-form-item>
    </n-form>

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">取消</n-button>
        <n-button type="primary" :loading="loading" @click="handleSave">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
  import { XUpload, XButton } from '@/components'
  import {
    NModal,
    NForm,
    NFormItem,
    NText,
    NInput,
    NInputGroup,
    NSpace,
    NButton,
    FormValidationError,
    useDialog
  } from 'naive-ui'
  import { useStore } from '@/store'
  import { computed, onMounted, reactive, ref } from 'vue'
  import { formatDate } from '@/utils'
  import { useDictionary } from '@/hooks'
  import { companySave } from '@/api/account'

  const store = useStore()
  const emits = defineEmits(['success'])
  const props = defineProps({
    modalData: {
      type: Object,
      default: () => ({})
    }
  })

  const getProps = reactive(props)
  const loading = ref(false)
  const loadingDetail = ref(false)
  const formRef = ref(null)
  const form = ref({
    companyId: '',
    companyName: '',
    licenseUrl: '',
    accountName: '',
    accountMobile: '',
    accountPassword: '',
    accountMailbox: ''
  })

  const rules = reactive({
    licenseUrl: { required: true, message: '请上传', trigger: 'change' },
    companyName: { required: true, message: '请输入', trigger: ['blur', 'change'] },
    accountName: { required: true, message: '请输入', trigger: ['blur', 'change'] },
    accountMobile: {
      required: true,
      message: '请输入正确的手机号',
      validator(rule: any, value: number) {
        if (/^1[3-9]\d{9}$/gi.test(String(value))) {
          return true
        } else {
          return new Error('请输入正确的手机号')
        }
      },
      trigger: ['blur', 'change']
    },
    accountPassword: {
      required: true,
      message: '密码必须是中英文6位以上',
      trigger: ['blur', 'change'],
      validator(rule: any, value: number) {
        const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/
        if (regex.test(String(value))) {
          return true
        } else {
          return new Error('密码必须包含中英文')
        }
      }
    },
    accountMailbox: { required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  })
  const title = props.modalData.type === 'add' ? '新增账户' : '编辑账户'

  onMounted(() => {
    if (props.modalData.type === 'edit') {
      form.value = props.modalData.row
    }
  })

  // 生成随机6位密码
  function generatePassword() {
    const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    const digits = '0123456789'
    const allChars = letters + digits

    let password = ''

    // Ensure at least one letter and one digit
    password += letters[Math.floor(Math.random() * letters.length)]
    password += digits[Math.floor(Math.random() * digits.length)]

    // Fill the remaining slots
    for (let i = 2; i < 6; i++) {
      password += allChars[Math.floor(Math.random() * allChars.length)]
    }

    // Shuffle the password to randomize the positions of the letter and digit
    password = password
      .split('')
      .sort(() => Math.random() - 0.5)
      .join('')

    return password
  }

  function setPwd() {
    form.value.accountPassword = generatePassword()
  }

  function handleClose() {
    getProps.modalData.show = false
  }

  function handleSave() {
    formRef.value?.validate(async (errors: Array<FormValidationError>) => {
      if (!errors) {
        submitData()
      } else {
        console.log(errors)
      }
    })
  }

  async function submitData() {
    loading.value = true
    const { data } = await store
      .dispatch('account/companySave', {
        ...form.value
      })
      .finally(() => {
        loading.value = false
      })
    emits('success', data)
    getProps.modalData.show = false
  }
</script>

<style scoped lang="scss"></style>
